;
(function (call) {
    var main = {
        dialCfg: [],
        userInfo: null,
        dialStatus: {
            '1': '拨号中',
            '2': '拨号失败',
            '3': '呼叫成功',
            '4': '无人接听'
        },
        areaName: {
            12: '天津市', 120111: '西青区', 120112: '津南区', 120113: '北辰区', 120114: '武清区', 120115: '宝坻区',
            120116: '滨海新区', 120221: '宁河区', 120223: '静海区', 120225: '蓟州区', 120110: '东丽区'
        },
        init: function () {
            this.bindEvt();
            this.initView();
        },
        initDatePicker: function () {

            this.qbTime = CafeJS.Datepicker({
                appendTo: "#startTime",
                type: 1,
                dateFmt: "yyyy-MM-dd"
            });
            this.ybTime = CafeJS.Datepicker({
                appendTo: "#endTime",
                type: 1,
                dateFmt: "yyyy-MM-dd"
            });
        },
        initView: function () {
            var that = this;
            that.initDatePicker();
            that.queryMsgSendUser();
            var userInfo = $("#userInfo").data('info');
            this.userInfo = userInfo;
            $.getJSON(api.internal.business.contacts, function (res) {
                if (!res.isSuccess) return;
                that.dialCfg = res.data.sort(function (a, b) {
                    return Number(a.areaCode) - Number(b.areaCode);
                })
                that.getDialData();
            });
            $("#modal_dial").find("#modal-title span").first().click();
        },
        // 初始化短信
        queryMsgSendUser: function () {
            $.getJSON(api.internal.business.queryMsgSendUser, function (res) {
                if (!res.isSuccess) return;
                var data = res.data, $dialUnit = $("#dialUnit").empty().append(`<option value="">全部</option>`);
                var $div = $('.msg-left').empty();
                for (var i = 0; i < data.length; i++) {
                    $dialUnit.append(`<option value="${data[i].areaCode}">${data[i].publishGroupName}</option>`)
                    var dl = '<dl><dt><i></i>' + data[i].publishGroupName + '</dt>'
                    for (var j = 0; j < data[i].publishUserList.length; j++) {
                        var nameList = data[i].publishUserList[j]
                        dl += '<dd><input type="checkbox">'
                        if (nameList.isAuto == 0) {
                            dl += '<span data-id=' + nameList.publishUserId + '>'
                        } else {
                            dl += '<span data-id=' + nameList.publishUserId + ' class="active">'
                        }
                        dl += nameList.publishUserName + ' ' + nameList.publishUserPhone + '</span></dd>'
                    }
                    dl += '</dl>'
                    var $dl = $(dl)
                    $dl.data('item', data[i])
                    $div.append($dl);
                }
                $('.msg-left dl dd').attr('style', 'display: none;');
                $('.msg-left dl:first-child dd').show();
                $('.msg-left dl dt').addClass('active');
                $('.msg-left dl:first-child dt').removeClass('active');
                $('.msg-left dl dt i').attr('style', 'transform: rotate(' + 90 + 'deg)');
                $('.msg-left dl:first-child dt i').attr('style', 'transform: rotate(' + 180 + 'deg)');
            });
        },
        // 修改短信接口
        updateMsgSendUser: function () {
            var that = this, publishUserList = [];
            $(".msg-left").find('dl').each(function (i, item) {
                var list = $(item).data('item').publishUserList;
                var $span = $(item).find('dd span.active');
                $span.each(function (j, item1) {
                    var obj2 = {};
                    obj2.areaCode = list[j].areaCode;
                    obj2.publishGroupId = list[j].publishGroupId;
                    obj2.publishUserId = $(item1).data('id');
                    obj2.publishUserName = $(item1).text().split(' ')[0];
                    obj2.publishUserPhone = $(item1).text().split(' ')[1];
                    obj2.isAuto = '1'
                    publishUserList.push(obj2)
                })
            })
            var param = { "publishUserList": publishUserList };
            $.ajax({
                type: "POST",
                url: api.internal.business.updateMsgSendUser,
                contentType: "application/json;charset=utf-8",
                dataType: 'json',
                data: JSON.stringify(param),
                success: function (res) {
                    if (res.isSuccess) {
                    }
                }
            })
        },
        // 发布短信
        sendMessage: function () {
            var that = this;
            var telPhones = $("#publishObjects").data('val');
            if (!telPhones) {
                alert('发布对象不能为空');
                return;
            }
            telPhones = telPhones.split("、")
            if (telPhones.length > 10) {
                alert('发送的号码最多选10个');
                return;
            }
            var content = $("#msgContent").val()
            var userId = that.userInfo.smuser.name
            if (!content) {
                alert('短信内容不能为空');
                return;
            }
            $.ajax({
                type: "post",
                url: api.internal.business.sendMessage,
                data: {
                    "content": content,
                    "telPhones": telPhones.join(','),
                    "userId": userId
                },
                success: function (res) {
                    if (res.isSuccess) {
                        alert('发布成功');
                    } else {
                        alert('发布失败');
                    }
                }
            })
        },
        getDialData: function () {
            var that = this;
            var time = CafeJS.jcyb.datepicker.getVal();
            $.getJSON(api.internal.business.getDialData + '/' + time, function (res) {
                if (res.isSuccess) {
                    that.buildView(res.data);
                };
            });
        },
        buildView: function (warnData) {
            var dial = $(".dial-content-left").empty();
            var dialRight = $(".dial-content-right").empty();
            for (var i = 0; i < this.dialCfg.length; i++) {
                var dialItem = this.dialCfg[i];

                //右部数据
                var $area = $(`<li><i></i><span>${dialItem.areaName}</span></li>`);
                dialRight.append($area);
                $(".dial-content-right li").first().addClass("active");
                $(".dial-content-right li i").first().addClass("active");

                //左部数据
                var li = '<li>' +
                    '<span class="area" code="' + dialItem.areaCode + '">' + dialItem.areaName + '</span>' +
                    '<ul class="code">'
                var number = dialItem.phone;
                if (!number) continue;
                var numberArr = number.split(',');
                li += '<li>'
                numberArr.forEach(function (number) {
                    li += '<span>' + number + '</span>';
                })
                li += '</li>'

                var warnList = warnData[key],
                    content = [];
                if (warnList && warnList.length > 0) {
                    warnList.forEach(function (data) {
                        content.push(data.content);
                    })
                }
                content = content.join('\n');
                if (content) {
                    $area.addClass("warn");
                }
                li += '</ul><div class="textarea"><textarea>' + content + '</textarea></div></li>'
                var $li = $(li);
                dial.append($li);
                $(".dial-content-left li span").first().addClass("active");
            }
        },
        // 拨号
        dialNumber: function () {
            var that = this;
            $(".dial-content-left>li").each(function (i, item) {
                var obj = {};
                var $code = $(item).find('.code li');
                var $content = $(item).find('.textarea textarea');
                var number = [];
                $code.find('span.active').each(function (i, num) {
                    number.push($(num).text());
                })
                if (number.length === 0) return false;

                var content = $content.val();

                if (content.length === 0) return false;

                obj.phoneNumbers = number.join(',');
                obj.data = { time: new Date().format('yyyy.MM.dd hh:mm'), weather: content, reason: '' };
                obj.modelId = 'TTS_175240833';
                obj.modelName = '更新预通报模板';
                var param = {
                    param: JSON.stringify(obj)
                }
                $.getJSON(api.external.dialNumber, param, function (res) {
                    if (res.code == '0')
                        that.alert('拨号成功');
                    else
                        that.alert('拨号失败');
                });
            });
        },
        // 重新拨号
        redialNumber: function (dialObj) {
            var that = this;
            var data = [{
                unit: dialObj.unit,
                levels: [{
                    level: 1,
                    number: dialObj.tel
                }],
                content: dialObj.content
            }]
            var param = {
                data: JSON.stringify(data)
            }
            $.getJSON(api.external.dialNumber, param, function (res) {
                var res = JSON.parse(res);
                that.alert('拨号成功');
            });
        },
        // 拨号记录,短信记录
        dialHistory: function () {
            var that = this;
            $('.record-table tbody').empty()
            var bid = $("#bidSelect").val()
            var unit = $("#dialUnit").val();
            var status = $("#dialStatus").val();
            if (bid == '1') {
                status = $("#msgStatus").val();
                unit = $("#dialUnit option:selected").text()
            }
            var startTime = this.qbTime.getVal().substr(0, 10) + ' 00:00:00';
            var endTime = this.ybTime.getVal().substr(0, 10) + ' 23:59:59';
            startTime = new Date(startTime).format('yyyyMMddhhmmss');
            endTime = new Date(endTime).format('yyyyMMddhhmmss');
            var param = {
                unit: unit == '全部' ? ' ' : unit,
                status: status,
                startTime: startTime,
                endTime: endTime
            }
            var url = api.external.dialHistory
            if (bid == '1') {
                param.startTime = this.qbTime.getVal().substr(0, 10) + ' 00:00:00';
                param.endTime = this.ybTime.getVal().substr(0, 10) + ' 23:59:59';
                url = api.internal.business.querySendMesHis
            }
            $.getJSON(url, param, function (res) {
                if (bid == '1') {
                    if (res.isSuccess && res.data != null) {
                        that.bulidMsgHistoryTable(res.data);
                    };
                } else {
                    if (!res || res.code != '0') return;
                    that.bulidHistoryTable(res.data, status);
                }
            });
        },
        buildTableHeader: function (bid) {
            $('.record-table tbody').empty();
            var $head = $(".record-table thead").empty();
            if (bid == 1) {
                $head.append(`<tr><th width="6%">序号</th><th width="14%">叫应时间</th>
                            <th width="8%">叫应人</th><th width="10%">发布对象</th>
                            <th width="22%">短信内容</th><th width="10%">叫应手段</th>
                            <th width="10%">叫应结果</th></tr>`);
            } else {
                $head.append(`<tr><th width="10%">序号</th> <th width="25%">拨打号码</th>
                <th width="25%">拨打时间</th> <th width="20%">状态</th> <th width="20%">操作</th></tr>`);
            }
        },
        bulidMsgHistoryTable: function (data) {
            var $tbody = $('.record-table tbody').empty();
            data.forEach(function (item, index) {
                var $tr = $(`
        			<tr>
                        <td width="6%">${index + 1}</td>
                        <td width="14%" title="${new Date(item.sendtime).format('yyyy-MM-dd hh:mm')}">${new Date(item.sendtime).format('MM-dd hh:mm')}</td>
                        <td width="8%">${item.contacter}</td>
                        <td width="10%">${item.phoneUserName}</td>
                        <td title="${item.content}" width="22%">${item.content}</td>
                        <td width="10%">短信</td>
                        <td width="10%">${item.reselt == '1' ? '成功' : '失败'}</td>
	                </tr>
        		`);
                $tr.find('td').last().data('obj', item);
                $tbody.append($tr);
            })
        },
        bulidHistoryTable: function (data, status) {
            var that = this;
            var $tbody = $('.record-table tbody').empty();
            data.forEach(function (item, index) {
				if (item.status != status) return;
                var $tr = $(`
        			<tr>
                    <td width="10%">${index + 1}</td>
                    <td width="25%">${item.phoneNumber}</td>
                    <td width="25%" title="${new Date(item.dateTime).format('yyyy-MM-dd hh:mm')}">${new Date(item.dateTime).format('MM-dd hh:mm')}</td>
                    <td width="20%">${that.dialStatus[item.status]}</td>
                    <td width="20%" class="numberBtn">重新拨打</td>
	                </tr>
        		`);
                $tr.find('td').last().data('obj', item);
                $tbody.append($tr);
            })
        },
        //弹出框内容
        alert: function (info) {
            $.dialogMaster({
                "type": 'tip',
                "info": info
            });
        },
        queryContactUser: function () {
            var that = this;
            var $content = $(".number-setting").empty();
            var $contentRight = $(".number-setting-right").empty();
            var code = Number(this.userInfo.userAreaCode);
            $.getJSON(api.internal.business.queryContactUser, function (res) {
                if (res.isSuccess) {
                    var data = res.data;
                    for (var key in data) {
                        if (data[key].length === 0) continue;
                        if (code == 12) {
                            var li = '<li data-code="' + key + '">'
                        } else {
                            if (code == key) {
                                var li = '<li data-code="' + key + '">'
                            } else {
                                var li = '<li class="disabled" data-code="' + key + '">'
                            }
                        }
                        li += '<span>' + that.areaName[key] + '</span><button id="addBtn">增 加</button>'
                        li += '<div id="editmsg' + key + '" class="editmsg">'
                        data[key].forEach(function (item) {
                            li += '<div class="editmsg-list">'
                            li += ' <input type="text" class="username" value="' + item.userName + '">'
                            li += ' <input type="number" class="phone" value="' + item.phone + '">'
                            li += ' <i id="removeBtn">×</i>'
                            li += ' </div>'
                        })
                        li += '</div></div></li>'
                        var $li = $(li)
                        $content.append($li);
                        $contentRight.append(`<li><i></i><span>${that.areaName[key]}</span></li>`);
                        $(".number-setting-right li").first().addClass("active");
                        $(".number-setting-right li i").first().addClass("active");
                    }
                }
            });
        },
        addNumberPop: function (areaCode) {
            $("#modal_add_number").remove()
            CafeJS.ModalBox({
                id: 'add_number',
                title: "新增联系人",
                width: 320,
                height: 170,
                m_top: 310,
                m_right: 780,
                hide: false,
                isBackdrop: true,
                url: api.internal.tpl.addNumberPop,
                createSucc: function () {
                }
            });
            $("#modal_add_number").data('code', areaCode)
        },
        saveNumberMsg: function () {
            var that = this;
            var data = [];
            $(".number-setting li").each(function (i, li) {
                var $list = $(li).find('.editmsg>div')
                $list.each(function (j, item) {
                    var obj = {};
                    obj.areaCode = $(li).data('code');
                    obj.phone = $(item).find('.phone').val();
                    obj.userName = $(item).find('.username').val();
                    data.push(obj)
                })
            })
            $.ajax({
                url: api.internal.business.contactSave,
                type: "POST",
                contentType: "application/json;charset=utf-8",
                dataType: 'json',
                data: JSON.stringify(data),
                success: function (res) {
                    if (res.isSuccess) {
                        that.alert('保存成功');
                        $(".setting-btn").click();
                    } else {
                        that.alert("保存失败");
                    }
                }
            })
        },
        // 初始化叫应策略
        queryCallStrategy: function (val) {
            var $body = $(".call-strategy-body").empty();
            if (val == '') {
                var $select = $("#callStrategySelect").empty().append(`<option value="">全部</option>`);
            }
            $.getJSON(api.internal.business.queryMsgSendUser, function (res) {
                if (!res.isSuccess) return;
                var data = res.data, dataArr = [];
                for (var i = 0; i < data.length; i++) {
                    if (val == '') {
                        $select.append(`<option value="${data[i].areaCode}">${data[i].publishGroupName}</option>`);
                    }
                    if (val == data[i].areaCode || val == '') {
                        for (var j = 0; j < data[i].publishUserList.length; j++) {
                            var list = data[i].publishUserList[j];
                            if (list.isAuto == '1') {
                                dataArr.push(list);
                            }
                        }
                    }
                }
                dataArr.forEach(function (item, i) {
                    var index = i + 1;
                    var div = '<div class="call-strategy-item"><div style="width:5%">' + index + '</div>'
                    div += '<div style="width:14%" title="' + item.publishUserPhone + '">' + item.publishUserName + '</div>'
                    div += '<div style="width:15%"><div><input type="checkbox" checked><span>短信</span></div>'
                    div += '<div><input type="checkbox"><span>电话</span></div></div>'
                    div += '<div style="width:8.6%"><input type="checkbox" checked></div>'
                    div += '<div style="width:9.25%"><input type="checkbox"></div>'
                    div += '<div style="width:10.65%"><input type="checkbox"></div>'
                    div += '<div style="width:10.65%"><input type="checkbox"></div>'
                    div += '<div style="width:5.1%"><input type="checkbox"></div>'
                    div += '<div style="width:7.25%"><input type="checkbox"></div>'
                    div += '<div style="width:5.1%"><input type="checkbox"></div>'
                    div += '<div style="width:9.35%"><input type="checkbox"></div></div>'
                    var $div = $(div);
                    $body.append($div);
                })
            });
        },
        bindEvt: function () {
            var that = this;
            $("#callStrategySelect").change(function () {
                var val = $(this).val();
                that.queryCallStrategy(val);
            })
            $("#modal_dial").find(".modal-title>span").click(function () {
                $(this).addClass("active").siblings().removeClass("active");
                $(".dial-content>li").eq($(this).index()).show().siblings().hide();
                if ($(this).hasClass("setting-btn")) {
                    that.queryContactUser();
                } else if ($(this).hasClass('call-strategy-btn')) {
                    that.queryCallStrategy('');
                }
            });
            $(".dial-content-left").scroll(function () {
                var scrollTop = $(".dial-content-left").scrollTop();
                $(".dial-content-left>li").each(function (e, item) {
                    var offsetTop = $(this).offset().top;
                    if (offsetTop && scrollTop > offsetTop - 100) {
                        $(".dial-content-right>li").eq(e).addClass("active").siblings().removeClass("active");
                        $(".dial-content-right>li").eq(e).find('i').addClass("active").parent().siblings().children('i').removeClass("active");
                        $(".dial-content-left>li>span").eq(e).addClass("active").parent().siblings().children('span').removeClass("active");
                    } else {
                        return false;
                    }
                })
            });
            $(".number-setting").scroll(function () {
                var scrollTop = $(".number-setting").scrollTop();
                $(".number-setting>li").each(function (e, item) {
                    var offsetTop = $(this).offset().top;
                    if (offsetTop && scrollTop > offsetTop - 100) {
                        $(".number-setting-right>li").eq(e).addClass("active").siblings().removeClass("active");
                        $(".number-setting-right>li").eq(e).find('i').addClass("active").parent().siblings().children('i').removeClass("active");
                        $(".number-setting>li>span").eq(e).addClass("active").parent().siblings().children('span').removeClass("active");
                    } else {
                        return false;
                    }
                })
            });
            $("#modal_dial .close").click(function () {
                window.smartDial = null;
                $("#modal_dial").remove();
                $("#dial").removeClass("active");
            });
            $(".dial-content-left").on('click', 'li .code li span', function () {
                $(this).toggleClass("active");
            });
            $(".dialBtn").click(function () {
                that.dialNumber();
            });
            $(".searchBtn").click(function () {
                that.dialHistory();
            });
            $(".record-table").on('click', ".numberBtn", function () {
                var obj = $(this).data('obj');
                that.redialNumber(obj);
            });
            $(".number-setting").on("click", ' li i#removeBtn', function () {
                $(this).parent().remove()
            }).on("click", ' li button#addBtn', function () {
                var areaCode = $(this).parent().data('code')
                that.addNumberPop(areaCode);
            })
            $("#saveBtn").click(function () {
                that.saveNumberMsg();
            })
            $("#bidSelect").change(function () {
                var val = $(this).val();
                that.buildTableHeader(val);
                if (val == 0) {
                    $("#dialStatus").show();
                    $("#msgStatus").hide();
                    $("#dialUnit").parent().hide();
                } else {
                    $("#dialStatus").hide();
                    $("#msgStatus").show();
                    $("#dialUnit").parent().show();
                }
            })
            $("#bidSelect").change();
            $("#searchBtn").click(function () {
                var dosearch = $.trim($("#searchText").val());//获取要查询的文字
                if (!dosearch) {
                    that.queryMsgSendUser()
                    return;
                }
                var dtree_div = $(".msg-left").find("dd").hide().filter(":contains('" + dosearch + "')");//获取所有包含文本的
                $(".msg-left").find("dt").addClass('active');
                $(".msg-left").find("i").attr('style', 'transform: rotate(' + 90 + 'deg)');
                $.each(dtree_div, function (index, element) {
                    $(element).show().show();
                    $(element).parent().find('dt').removeClass('active');
                    $(element).parent().find('i').attr('style', 'transform: rotate(' + 180 + 'deg)').siblings().find('i').attr('style', 'transform: rotate(' + 90 + 'deg)');
                });
            })
            $(".msg-left").on('click', 'dl dt', function () {
                $(this).toggleClass('active')
                if ($(this).hasClass('active')) {
                    $(this).parent().find('dd').hide();
                    $(this).find('i').attr('style', 'transform: rotate(' + 90 + 'deg)');
                } else {
                    $(this).parent().find('dd').show();
                    $(this).find('i').attr('style', 'transform: rotate(' + 180 + 'deg)');
                }
            }).on('click', 'dl dd input', function (e) {
                var publishObjs = [], publishVals = [];
                var $div = $("#publishObjects").empty()
                $(".msg-left").find('dl dd input').each(function (i, item) {
                    if ($(item).is(':checked')) {
                        var msgName = $(item).siblings('span').text().split(' ');
                        publishObjs.push(msgName[0]);
                        publishVals.push(msgName[1]);
                    }
                })
                if ($(this).is(":checked")) {
                    $("#publishObjects").data('val', publishVals.join("、"));
                    publishObjs.forEach(function (item, i) {
                        $div.append(`<span><a>${item}</a> <a>${publishVals[i]}</a></span>`);
                    })
                } else {
                    $("#publishObjects").data('val', publishVals.join("、"));
                    publishObjs.forEach(function (item, i) {
                        $div.append(`<span><a>${item}</a> <a>${publishVals[i]}</a></span>`);
                    })
                }
            }).on('click', 'dl dd span', function () {
                if (that.userInfo.smuser.iid == 2) {
                    $(this).toggleClass('active')
                    that.updateMsgSendUser();
                }
            })
            $(".publishBtn").click(function () {
                that.sendMessage();
            })
            $(".downloadBtn").click(function () {
                $.exportExcel({
                    tableNm: '叫应历史统计',
                    tableId: 'recordTable'
                })
            })
            $(document).keyup(function (event) {
                if (event.keyCode == 13) {
                    $("#searchBtn").trigger("click");
                }
            });
        },
    };
    window.smartDial = main;
    if (typeof call === 'function') {
        call(main);
    }
})(function (main) {
    CafeJS.models(['datepicker'], function () {
        main.init();
    });
});